/**
 * @author yxw
 * date : 2013年10月24日 下午1:20:53 
 */
package com.tzinfo.tzt.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.ImagePagerAdapter;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.NewhouseBuyInfo;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;
import com.tzinfo.tzt.util.ValidityTools;

public class TuangouDetailActivity extends BaseActivity implements
		OnClickListener {

	private NewhouseBuyInfo newhouseBuyInfo;
	private String tuanPhone="";
	private Dialog dialog;
	private String sHouseId = "";
	private MyResultList newhouseBuySignResult;
	
	private List<Map<String, Object>> imgData;
	// UI组件
	private Button backBtn, getPreBtn;
	private EditText phoneNumEidtText;
	private TextView[] textView = new TextView[7];
	private ImageView imageView;
	private ViewPager imagesPager;
	private ImagePagerAdapter imagePagerAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tuangou_detail);
		Intent thisIntent = this.getIntent();
		sHouseId=thisIntent.getStringExtra("houseId");
		newhouseBuyInfo = (NewhouseBuyInfo) thisIntent
				.getSerializableExtra("newhouseBuyInfo");
		init();
		if (null!=newhouseBuyInfo)
		setData();
	}

	private void init() {
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		getPreBtn = (Button) this.findViewById(R.id.bt_get_tuan);
		getPreBtn.setOnClickListener(this);

		textView[0] = (TextView) this.findViewById(R.id.text_Infos_Name);
		textView[1] = (TextView) this.findViewById(R.id.text_Infos_Sales);
		textView[2] = (TextView) this.findViewById(R.id.text_Infos_Caption);
		textView[3] = (TextView) this.findViewById(R.id.text_Infos_SignCount);
		textView[4] = (TextView) this.findViewById(R.id.text_Infos_RemainTime);
		textView[5] = (TextView) this.findViewById(R.id.text_Infos_Introduce);
		textView[6] = (TextView) this.findViewById(R.id.text_Infos_Notice);
		imageView = (ImageView) this.findViewById(R.id.img_icon_Y_N);
		imagesPager = (ViewPager) this.findViewById(R.id.pager_images);
		phoneNumEidtText =(EditText) this.findViewById(R.id.et_tuan_phone);
		
		
		dialog = new MyProgressDialog(this).createDialog(getResources()
				.getString(R.string.loading));
	}

	private void setData() {

		if (!"".equals(newhouseBuyInfo.getName().trim())) {
			textView[0].setText(newhouseBuyInfo.getName().trim() + "·");
		}
		if (!"".equals(newhouseBuyInfo.getSales().trim())) {
			textView[1].setText(newhouseBuyInfo.getSales().trim());
		}
		if (!"".equals(newhouseBuyInfo.getCaption().trim())) {
			textView[2].setText(newhouseBuyInfo.getCaption().trim());
		}
		if (!"".equals(newhouseBuyInfo.getSignCount().trim())) {
			textView[3].setText(newhouseBuyInfo.getSignCount().trim() + "人已报名");
		}
		if (!"".equals(newhouseBuyInfo.getRemainTime().trim())) {
			textView[4].setText(newhouseBuyInfo.getRemainTime().trim());
		}
		if (!"".equals(newhouseBuyInfo.getIntroduce().trim())) {
			textView[5].setText(newhouseBuyInfo.getIntroduce().trim());
		}
		if (!"".equals(newhouseBuyInfo.getNotice().trim())) {
			textView[6].setText(newhouseBuyInfo.getNotice().trim());
		}
		if (newhouseBuyInfo.isIsGroup()) {
			imageView.setImageResource(R.drawable.xinfang_icon_exist);
		} else {
			imageView.setImageResource(R.drawable.xinfang_icon_default);
		}

		getData();
		imagePagerAdapter = new ImagePagerAdapter(this, imgData,
				R.layout.item_pager_image, new String[] { "img" },
				new int[] { R.id.image });
		imagesPager.setAdapter(imagePagerAdapter);
		imagesPager.setCurrentItem(0);
	}

	private void getData() {
		imgData = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		Log.e("size", newhouseBuyInfo.getPics().size() + "");
		List<String> pics = newhouseBuyInfo.getPics();

		if (pics == null || pics.size() == 0) {
			map = new HashMap<String, Object>();
			map.put("img", R.drawable.ic_empty);
			imgData.add(map);
		}
		for (int i = 0; i < pics.size(); i++) {
			map = new HashMap<String, Object>();
			map.put("img", pics.get(i));
			imgData.add(map);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			this.finish();
			break;
		case R.id.bt_get_tuan:
			// 检测手机号合法性
			tuanPhone = phoneNumEidtText.getText().toString();
			if (ValidityTools.checkPhoneNum(tuanPhone)) {
				// 加载进度条
				dialog.show();
				// 发送团购请求
				new Thread(getNewhouseBuySignRun).start();
			} else {
				Toast.makeText(this, "请输入正确的手机号", 5000).show();
			}

			break;
		default:
			break;
		}

	}

	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				getDataError((String) msg.obj);
				break;
			case 5:
				break;
			case 11:
				tuanService.saveNewhouseBuyInfoJson(newhouseBuyInfo);
				showMessage("恭喜你，团购成功!");
				dialog.dismiss();
				break;
			case -11:
				showMessage("抱歉，团购失败，请重试！\n"+(String) msg.obj);
				dialog.dismiss();
				break;
			}
		}
	};
	
	
	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						dialog.show();
						new Thread(getNewhouseBuySignRun).start();
					}
				}).show();
	}
	/**
	 * 线程 得到团购内容
	 */
	Runnable getNewhouseBuySignRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String url=AppDataConfig.xinfangUrl
					+ AppDataConfig.NewhouseBuySign + "?houseid=" + sHouseId
					+"&mobile="+tuanPhone;
			Log.e("url",url);
			jsonString = HttpTools.getJsonContent(url);
			Log.e("JsonString", jsonString);
			newhouseBuySignResult = JsonTools.getNewhouseBuySignResult(jsonString);
			if (newhouseBuySignResult.getSuccess()) {
				msg.arg1 = 11;
			} else {
				msg.arg1 = -11;
				msg.obj = newhouseBuySignResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	protected void showMessage(String msg){
		Toast.makeText(this, msg, 5000).show();
	}
}
